<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 文件分享控制器
 * @author xuelange
 * @modifier: Skiychan <developer@zzzzy.com>
 */
class Share extends MY_Controller{
	
	public function __construct(){
		parent::__construct();
        $this->load->service('share_service');
	}

    /**
     * 新增/修改分享
     * @return string
     */
	private function add($share_code,$slist,$list_md5,$password,$name="")
	{
		$share = array(
			"name" => $name, //$list_name
			"share_code" => $share_code,
            'share_code_hash' => Common::time33($share_code),
            'list_md5' => $list_md5,
            'list_md5_hash' => Common::time33($list_md5),
			'password' => $password,
			'uid' => $this->uid,
			"creation_ts" => time()
		);

        //添加分享
		$flag = $this->share_service->add($share, $slist);
		if (!$flag){
			Common::ajax_return($this->share_service);
		}
		$share['id'] = $this->share_service->last_share_id;

        $this->update_shared($slist, 1);
        return $share;

	}

    /**
     * 添加分享标签
     * @param $slist 分享列表
     */
    public function update_shared($slist, $switch=1) {
        if (! is_array($slist) && (count($slist) == 0)) return NULL;

        $datas = array();
        foreach ($slist as $keys => $values) {
            if ($values['ctype'] == 1) {
                $datas['files'][] = $values['c_uuid'];
            } else if ($values['ctype'] == 2) {
                $datas['folders'][] = $values['c_uuid'];
            }
        }

        if (isset($datas['files']))
            $this->share_service->update_shared_batch($this->uid, $datas['files'], $switch);

        if (isset($datas['folders']))
            $this->share_service->update_files_shared($this->uid, $datas['folders'], $switch);
    }

    /**
     * 邮件分享
     * @return string
     */
	public function send_email(){
		$sl_uuid = $this->input->post('sl_uuid'); //分享链接uuid
		$share_name = $this->input->post('share_name'); //分享名称
		$ps = $this->input->post('ps');
		//$content = $this->input->post('content'); //内容
		$mails = $this->input->post('mails');
		$pwd = $this->input->post('pwd');

		if (!$mails) return Common::prf_json(FALSE,NULL,NULL,time(),TRUE,'没有可发送的邮件');

		$arr = explode(',', $mails);
		$arr = array_flip(array_flip($arr));
		$mails = implode(',', $arr);
		$uemail = '';
		$footHtml ='';
		$friendHtml = '';

		if(!$this->login_service->is_tryout() && !empty($this->uemail)){
			$uemail = $this->uemail;
			$footHtml = '<div style="font-size:12px; text-align:center; color:#8e8e8e; padding:8px 6px; background-color:#eef4ff;">这是一封由易控系统自动转发的分享邮件，不能直接回复。</div>';
			$friendHtml = '<a style="color:#73aeff; margin:0 6px;" href="mailto:'.$uemail.'">'.$uemail.'</a>';
			$subject = $uemail.'(发件人邮箱)通过易控云端给你分享了文件';
		} else {
			$subject = '您的好友通过易控云端给你分享了文件';
		}
		
		//加载CI的email类
		$this->load->library('email');
		//以下设置Email内容

		$host = site_url();
		$url =  site_url('s/'.$sl_uuid);
		$pwdHtml = '';
		if($pwd){
			$pwdHtml = '<span style="margin-left:8px;">(密码:'.$pwd.')</span>';
		}
		$html = <<<EOT
		<style type="text/css">
		*{margin:0; padding:0;}
		</style>
		<div style="width:600px; margin:0 auto; font:14px/1.5 Microsoft Yahei UI,Microsoft Yahei,tahoma,arial,宋体; background-color:#fbfbfb;">
		<div><a href="{$host}" target="_blank"><img src="{$host}/static/img/email/logo.png" alt="易控"></a></div>
		<div style="color:#5f5f5f; font-size:13px; margin:32px 37px 40px 37px; line-height:25px;">
			<p style="margin-bottom:10px;">您的好友{$friendHtml} <strong>(点击地址回复邮件)</strong>给你分享了TA在易控云端上的文件：</p>
			<h3 style="font-size:16px; color:#5f5f5f; margin-bottom:27px;"><p style="float:left;"><img src="{$host}/static/img/email/file-icon.png" alt="文件" style="margin-right:10px;"></p><p style="float:left; overflow: hidden; text-overflow: ellipsis; width: 500px; white-space: nowrap;" title="{$share_name}">{$share_name}</p></h3>
			<p style="font-size:12px; color:#7c7b7b; clear:both; border: 1px solid #eee;padding: 10px;">{$ps}</p>
			<p style="text-align:center; margin:35px 0;"><a href="{$url}" target="_blank" style="color: #ffffff; display: inline-block; font-size: 18px; height: 43px; line-height: 38px; width: 146px; background-color: #81abf8; border: 1px solid #7aa5f3; border-radius: 1px;  box-shadow: 0 -3px #6c98f5 inset; cursor: pointer; text-align: center; text-decoration:none;">打开</a></p>
			<p>如果以上按钮点击无效，请将下面的链接地址复制到您的浏览器地址栏（如IE）</p>
			<p><a href="{$url}" target="_blank" style="color:#73aeff; word-break: break-all; text-decoration:none;">{$url}</a>{$pwdHtml}</p>
		</div>
		{$footHtml}
		<div style="font-size:12px; color:#8e8e8e; margin:20px 37px 0 37px; text-align:center;">©2016 易控<img src="{$host}/static/img/email/logo-info.png" alt="我的信息我做主" style="vertical-align: middle; margin-left: 12px;"></div>
	</div>
EOT;
		$this->email->from('waifa@wowostar.com', '易控');
        $this->email->reply_to($uemail, $uemail);
		//$this->email->to($mails);
		$this->email->bcc($mails);  //密送，10个一批发送
		$this->email->subject($subject);
		$this->email->message($html);
		$this->email->send();

		//保存历史
		$history = $this->share_service->get_share_receivers($this->uid, 1);
		if(!$history){
			$data = array(
					'uid' => $this->uid,
                    'type' => 1,
					'receiver' => $mails,
                    'creation_ts' => time()
			);
			$this->share_model->insert_receivers($data);
		} else {
			$mails = $history['receiver'] . ',' . $mails;
			$arr = explode(',', $mails);
			$arr = array_flip(array_flip($arr));  //去重
			$mails = implode(',', $arr);
			$data = array(
					'receiver' => $mails,
                    'modify_ts' => time()
			);
			$this->share_model->update_receivers(array("uid"=>$this->uid,"type"=>1),$data);
		}

        return Common::prf_json(TRUE,NULL);
	}

    /**
     * 取得分享的邮件列表
     * @return string
     */
	public function get_history_email(){
		$result = $this->share_service->get_share_receivers($this->uid, 1);
		if(!$result) return Common::prf_json(FALSE,NULL,NULL,time(),TRUE,'没有历史记录');

		$mails = $result['receiver'];
		$arr = explode(',', $mails);
		$arr = array_flip(array_flip($arr));
		$data = array();
		foreach($arr as $v){
			$data[] = $v;
		}

		return Common::prf_json(TRUE, $data);
	}

    /**
     * 检测分享的文件或文件夹的文件 是否有分享权限
     * @param $datas 文件和文件夹信息
     * @return array
     */
    private function check_file($datas) {
        //$datas = $this->input->post('data');

        if (empty($datas) || !is_array($datas)) {
			Common::ajax_return(1003);
            //return array('ret' => 1, 'error' => '请求参数错误');
        }

        $infos = array();
        //文件分类
        foreach ($datas as $keys => $f) {
            if ($f['ctype'] == 2) {
                $infos['folders'][] = $f['c_uuid'];
            } else if ($f['ctype'] == 1) {
                $infos['files'][] = $f['c_uuid'];
            }
        }

        //文件
        if (isset($infos['files'])) {
            $file_list = $this->share_service->get_file_list($this->uid, $infos['files']);
            if (! empty($file_list))
                return TRUE;
        }

        //文件夹
        if (isset($infos['folders'])) {
            $folder_files = $this->share_service->get_folder_files($this->uid, $infos['folders']);
			/*if ( empty($folder_files['files']) ) {
				Common::ajax_return(7103);
			}*/
            //无文件 , 全部的文件夹均不可分享
            if ( empty($folder_files['files']) || ! isset($folder_files['fds']['pass'])) {
				Common::ajax_return(7103);
				//return array('ret' => 1, 'error' => "所选项中没有可分享的文件");
            }

            $unpass_fds = isset($folder_files['fds']['unpass']) ? $folder_files['fds']['unpass'] : array();
            foreach ($folder_files['files'] as $keys => $l_file) {
                if (($l_file['access_denied'] == 0) && ($l_file['deleted'] == 0)) {

					if (empty($unpass_fds))
						return true;

                    //该文件的父级目录是否拒绝访问
                    if (! in_array($l_file['folder_id'], $unpass_fds)) {
						return TRUE;
                    }
                }
            }
			Common::ajax_return(7103);
        }
		else{
			Common::ajax_return(7001);
		}

        //return array('ret' => 1, "error" => "所选项中没有可分享的文件");
    }

    /**
     * 获取分享模板和生成分享链接
     * @author: Skiychan
     */
    public function to_share() {
		$uuid_info = $this->input->post('uuid', true);
		$name = $this->input->post('name', true);
		if(empty($uuid_info) || '' === $name)
		{
			Common::ajax_return(1003);
			//show_404();
		}
		$this->check_file($uuid_info);
		/*if($check['ret']!=-1)
		{
			echo json_encode($check);
			return TRUE;
		}*/
        /*$tmp_url = "static/page/copy_share.html";
        $tmp = file_get_contents($tmp_url);*/

        //if (! $uuid_info) return FALSE;
        $arr_avgs = array(
            'file' => array(),
            'folder' => array()
        );
        foreach ($uuid_info as $val) {
            if ($val['ctype'] == 1) {
                $arr_avgs['file'][] = $val['c_uuid'];
            } else {
                $arr_avgs['folder'][] = $val['c_uuid'];
            }
        }

        //sort($uuid_arr); //排序
        //$list_str = implode(',', $uuid_arr);
        $list_str = $this->share_service->create_file_str($arr_avgs['file'], $arr_avgs['folder']);
        $list_md5 = md5($list_str);  //添加,连接符

        $res = $this->share_service->check_share_code($list_md5);
        if (empty($res)) {
            $share_codes = $this->share_service->short_code($list_str.time(), FALSE);
            $share_code = $share_codes[0];
			$add_ret = $this->add($share_code,$uuid_info,$list_md5,"",$name);
			$share_code = $add_ret['share_code'];
			$share_id = $add_ret['id'];
        } else {

			//如果已存在分享，则判断是否移动过文件，若移动过则清除此share_code
			$share_files = $this->share_service->get_files_lid($res['id']);
			//新建分享列表和原有分享列表文件数不等,重新生成share_list
			if (count($share_files) != count($uuid_info)) {
				//删除分享列表的文件
				$del_files_lid = $this->share_service->delete_files_lid($res['id']);
				$list_arr = array();
				foreach ($uuid_info as $keys => $values) {
					$list_arr[$keys]['lid'] = $res['id'];
					$list_arr[$keys]['type'] = $values['ctype'];
					$list_arr[$keys]['fid'] = $values['c_uuid'];
				}
				//添加列表到list表
				$this->share_model->insert_share_list($list_arr);
			}

            $share_code = $res['share_code'];
            $share_pwd = $res['password'];
			$share_id = $res['id'];
        }
        $result = array('share_code' => $share_code);
        if (isset($share_pwd)) $result['password'] = $share_pwd;
        if (isset($share_id)) $result['share_id'] = $share_id;

        Common::ajax_return(0,NULL,$result,FALSE);
    }

	/**
	 * 设置分享密码
	 */
	public function set_password(){
		//update_share
		$password = $this->input->post("password",TRUE);
		$share_id = $this->input->post("share_id",TRUE);
		if(empty($share_id)){
			Common::ajax_return(1003);
		}
		$this->share_service->update_share(array("id"=>$share_id),array("password"=>$password));
		Common::ajax_return($this->share_service);

	}
}
